package com.xinan.system.curd;

import com.jfinal.aop.Before;
import com.jfinal.core.BaseController;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SearchSql;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.xinan.utils.Assert;
import com.xinan.utils.Constants;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * CommonController
 */
public class CurdSetController extends BaseController {
	
	public void index() {
		render("/WEB-INF/views/common/curdSet.html");
	}

    @Before(SearchSql.class)
	public void query() {
		int pageNumber = getParaToInt("page");
		int pageSize = getParaToInt("rows");
        String where = getAttr(Const.SEARCH_SQL);
		Page<CurdMeta> page = CurdMeta.dao.page(pageNumber, pageSize, where);
		   Map root = new HashMap();
			root.put("total", page.getTotalRow());
			root.put("rows", page.getList());
			renderJson(JsonKit.toJson(root));
	}
	
	public void save() {
        getModel(CurdMeta.class).save();
        renderText(Constants.SAVESUCCESS);
	}
	
	public void update() {
        getModel(CurdMeta.class).update();
        renderText(Constants.EDITSUCCESS);
	}
	
	public void delete() {
        CurdMeta.dao.deleteById(getParaToInt());
        renderText(Constants.DELETESUCCESS);
	}

    public void queryTables() {
        List<Record> list = TableMeta.dao.findAllTables();
        renderJson(list);
    }

    public void queryFields() {
    	String tableName = getPara("tablename");
    	Assert.hasText(tableName, "表字段查询时，表名不能为空！");
        List<Record> list = TableMeta.dao.findAllFields(tableName);
        renderJson(list);
    }
}
